import UIKit
import CoreImage
import CoreML
import Vision

extension ImageProcessor {
    func resizeImage(_ image: UIImage, to targetSize: CGSize) async throws -> UIImage {
        UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
        defer { UIGraphicsEndImageContext() }
        
        let aspectRatio = image.size.width / image.size.height
        var drawRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
        
        if aspectRatio > 1 {
            drawRect.size.height = targetSize.height / aspectRatio
            drawRect.origin.y = (targetSize.height - drawRect.height) / 2
        } else {
            drawRect.size.width = targetSize.width * aspectRatio
            drawRect.origin.x = (targetSize.width - drawRect.width) / 2
        }
        
        image.draw(in: drawRect)
        
        guard let resizedImage = UIGraphicsGetImageFromCurrentImageContext() else {
            throw ImageProcessingError.resizeFailed
        }
        
        return resizedImage
    }
    
    func createPixelBuffer(from image: UIImage) throws -> CVPixelBuffer {
        guard let cgImage = image.cgImage else {
            throw ImageProcessingError.invalidImage
        }
        
        let width = cgImage.width
        let height = cgImage.height
        
        let attrs = [
            kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue,
            kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue
        ] as CFDictionary
        
        var pixelBuffer: CVPixelBuffer?
        let status = CVPixelBufferCreate(
            kCFAllocatorDefault,
            width,
            height,
            kCVPixelFormatType_32BGRA,
            attrs,
            &pixelBuffer
        )
        
        guard status == kCVReturnSuccess, let buffer = pixelBuffer else {
            throw ImageProcessingError.pixelBufferCreationFailed
        }
        
        CVPixelBufferLockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0))
        defer { CVPixelBufferUnlockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0)) }
        
        let context = CGContext(
            data: CVPixelBufferGetBaseAddress(buffer),
            width: width,
            height: height,
            bitsPerComponent: 8,
            bytesPerRow: CVPixelBufferGetBytesPerRow(buffer),
            space: CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
        )
        
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        return buffer
    }
    
    func createOutputImage(from pixelBuffer: CVPixelBuffer) throws -> UIImage {
        let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
        let context = CIContext(options: [.useSoftwareRenderer: false])
        
        guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else {
            throw ImageProcessingError.outputImageCreationFailed
        }
        
        return UIImage(cgImage: cgImage)
    }
}

enum ImageProcessingError: Error {
    case resizeFailed
    case invalidImage
    case pixelBufferCreationFailed
    case outputImageCreationFailed
} 